const { Video, VideoLike, User, Comment } = require('../models');
const { generateUniqueId } = require('../utils/authUtils');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');

// 创建视频
const createVideo = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { title, video_url, description, thumbnail_url } = req.body;
    const userId = req.user.id;

    // 创建视频记录
    const video = await Video.create({
      id: generateUniqueId(),
      title,
      video_url,
      description,
      thumbnail_url,
      user_id: userId,
      created_at: new Date()
    });

    res.status(201).json({ message: '视频上传成功', videoId: video.id });
  } catch (error) {
    console.error('创建视频失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取视频列表
const getVideos = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', userId = '', sort = 'latest' } = req.query;
    
    const offset = (page - 1) * limit;
    
    const where = {};
    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ];
    }
    if (userId) {
      where.user_id = userId;
    }

    let order;
    switch (sort) {
      case 'popular':
        order = [['likes', 'DESC']];
        break;
      case 'oldest':
        order = [['created_at', 'ASC']];
        break;
      case 'latest':
      default:
        order = [['created_at', 'DESC']];
    }

    const { count, rows: videos } = await Video.findAndCountAll({
      where,
      include: [
        { model: User, attributes: ['id', 'username', 'avatar'] }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order
    });

    const formattedVideos = videos.map(video => ({
      id: video.id,
      title: video.title,
      video_url: video.video_url,
      description: video.description,
      thumbnail_url: video.thumbnail_url,
      user: {
        id: video.User.id,
        username: video.User.username,
        avatar: video.User.avatar
      },
      likes: video.likes || 0,
      views: video.views || 0,
      comments: video.comments || 0,
      created_at: video.created_at
    }));

    res.status(200).json({
      videos: formattedVideos,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取视频列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取单个视频
const getVideoById = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找视频
    const video = await Video.findByPk(id, {
      include: [
        { model: User, attributes: ['id', 'username', 'avatar'] },
        { 
          model: Comment, 
          include: [{ model: User, attributes: ['id', 'username', 'avatar'] }],
          order: [['created_at', 'DESC']]
        }
      ]
    });
    
    if (!video) {
      return res.status(404).json({ message: '视频不存在' });
    }

    // 增加观看次数
    await video.increment('views');

    // 检查当前用户是否点赞
    let isLiked = false;
    if (req.user) {
      const like = await VideoLike.findOne({
        where: { user_id: req.user.id, video_id: id }
      });
      isLiked = !!like;
    }

    const formattedVideo = {
      id: video.id,
      title: video.title,
      video_url: video.video_url,
      description: video.description,
      thumbnail_url: video.thumbnail_url,
      user: {
        id: video.User.id,
        username: video.User.username,
        avatar: video.User.avatar
      },
      likes: video.likes || 0,
      views: video.views || 0,
      comments: video.Comments.map(comment => ({
        id: comment.id,
        content: comment.content,
        user: {
          id: comment.User.id,
          username: comment.User.username,
          avatar: comment.User.avatar
        },
        created_at: comment.created_at
      })),
      isLiked,
      created_at: video.created_at
    };

    res.status(200).json(formattedVideo);
  } catch (error) {
    console.error('获取视频详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新视频
const updateVideo = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { id } = req.params;
    const { title, description, thumbnail_url } = req.body;
    const userId = req.user.id;

    // 查找视频
    const video = await Video.findByPk(id);
    if (!video) {
      return res.status(404).json({ message: '视频不存在' });
    }

    // 检查权限
    if (video.user_id !== userId) {
      return res.status(403).json({ message: '没有权限修改此视频' });
    }

    // 更新视频信息
    await video.update({ title, description, thumbnail_url });

    res.status(200).json({ message: '视频更新成功' });
  } catch (error) {
    console.error('更新视频失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除视频
const deleteVideo = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 查找视频
    const video = await Video.findByPk(id);
    if (!video) {
      return res.status(404).json({ message: '视频不存在' });
    }

    // 检查权限
    if (video.user_id !== userId) {
      return res.status(403).json({ message: '没有权限删除此视频' });
    }

    // 删除视频（会级联删除相关的点赞和评论）
    await video.destroy();

    res.status(200).json({ message: '视频删除成功' });
  } catch (error) {
    console.error('删除视频失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员删除视频
const adminDeleteVideo = async (req, res) => {
  try {
    const { id } = req.params;

    // 查找视频
    const video = await Video.findByPk(id);
    if (!video) {
      return res.status(404).json({ message: '视频不存在' });
    }

    // 管理员可以直接删除
    await video.destroy();

    res.status(200).json({ message: '视频删除成功' });
  } catch (error) {
    console.error('删除视频失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 点赞视频
const likeVideo = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 检查视频是否存在
    const video = await Video.findByPk(id);
    if (!video) {
      return res.status(404).json({ message: '视频不存在' });
    }

    // 检查是否已经点赞
    const existingLike = await VideoLike.findOne({
      where: { user_id: userId, video_id: id }
    });

    if (existingLike) {
      return res.status(400).json({ message: '已经点赞过了' });
    }

    // 创建点赞记录
    await VideoLike.create({
      id: generateUniqueId(),
      user_id: userId,
      video_id: id,
      created_at: new Date()
    });

    // 更新视频点赞数
    await video.increment('likes');

    res.status(200).json({ message: '点赞成功' });
  } catch (error) {
    console.error('点赞视频失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 取消点赞视频
const unlikeVideo = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 检查视频是否存在
    const video = await Video.findByPk(id);
    if (!video) {
      return res.status(404).json({ message: '视频不存在' });
    }

    // 删除点赞记录
    const result = await VideoLike.destroy({
      where: { user_id: userId, video_id: id }
    });

    if (result === 0) {
      return res.status(400).json({ message: '尚未点赞' });
    }

    // 更新视频点赞数
    await video.decrement('likes');

    res.status(200).json({ message: '取消点赞成功' });
  } catch (error) {
    console.error('取消点赞失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  createVideo,
  getVideos,
  getVideoById,
  updateVideo,
  deleteVideo,
  adminDeleteVideo,
  likeVideo,
  unlikeVideo
};